home *** CD-ROM | disk | FTP | other *** search
/ SGI Developer Toolbox 6.1 / SGI Developer Toolbox 6.1 - Disc 4.iso / public / ghostscript / src / gdevcdj.c < prev    next >
C/C++ Source or Header  |  1994-08-01  |  49KB  |  1,526 lines

  1. /* Copyright (C) 1991, 1992, 1993 Aladdin Enterprises.  All rights reserved.
  2.  
  3. This file is part of Ghostscript.
  4.  
  5. Ghostscript is distributed in the hope that it will be useful, but
  6. WITHOUT ANY WARRANTY.  No author or distributor accepts responsibility
  7. to anyone for the consequences of using it or for whether it serves any
  8. particular purpose or works at all, unless he says so in writing.  Refer
  9. to the Ghostscript General Public License for full details.
  10.  
  11. Everyone is granted permission to copy, modify and redistribute
  12. Ghostscript, but only under the conditions described in the Ghostscript
  13. General Public License.  A copy of this license is supposed to have been
  14. given to you along with Ghostscript so you can know your rights and
  15. responsibilities.  It should be in a file named COPYING.  Among other
  16. things, the copyright notice and this notice must be preserved on all
  17. copies.  */
  18.  
  19. /* gdevcdj.c */
  20. /* H-P colour printer drivers for Ghostscript */
  21. #include "std.h"                /* to stop stdlib.h redefining types */
  22. #include <stdlib.h>        /* for rand() */
  23. #include "gdevprn.h"
  24. #include "gdevpcl.h"
  25. #include "gsprops.h"
  26.  
  27. /***
  28.  *** Note: this driver was contributed by a user, George Cameron:
  29.  ***       please contact g.cameron@biomed.abdn.ac.uk if you have questions.
  30.  ***/
  31.  
  32. /*
  33.  * Note that there are six drivers contained in this code:
  34.  *
  35.  *     1 - cdj500:      HP DeskJet 500C
  36.  *     2 - cdj550:      HP DeskJet 550C
  37.  *     3 - pjxl300:     HP PaintJet XL300
  38.  *     4 - pj:          HP PaintJet
  39.  *     5 - pjxl:        HP PaintJet XL
  40.  *     6 - declj250:    DEC LJ250
  41.  *
  42.  * All of these drivers have 8-bit (monochrome), 16-bit and 24-bit
  43.  *     (colour) and for the DJ 550C 32-bit, (colour, cmyk mode)
  44.  *     options in addition to the usual 1-bit and 3-bit modes
  45.  * It is also possible to set various printer-specific parameters
  46.  *     from the gs command line, eg.
  47.  *
  48.  *  gs -sDEVICE=cdj550 -dBitsPerPixel=16 -dDepletion=1 -dShingling=2 tiger.ps
  49.  *
  50.  * Please consult the appropriate section in the devices.doc file for
  51.  * further details on all these drivers.
  52.  */
  53.  
  54. #define DESKJET_PRINT_LIMIT  0.04       /* 'real' top margin? */
  55. #define PAINTJET_PRINT_LIMIT 0.0        /* This is a guess.. */
  56.  
  57. /* Margins are left, bottom, right, top. */
  58. #define DESKJET_MARGINS_LETTER   0.25, 0.50, 0.25, 0.167
  59. #define DESKJET_MARGINS_A4       0.125, 0.50, 0.143, 0.167
  60. #define PAINTJET_MARGINS_LETTER  0.167, 0.167, 0.167, 0.167
  61. #define PAINTJET_MARGINS_A4      0.167, 0.167, 0.167, 0.167
  62. #define PAINTJET_MARGINS_A3      0.167, 0.167, 0.167, 0.167
  63.  
  64. /* Default page size is US-Letter or A4 (other sizes from command line) */
  65. #ifndef A4
  66. #  define WIDTH_10THS            85
  67. #  define HEIGHT_10THS           110
  68. #else
  69. #  define WIDTH_10THS            83      /* 210mm */
  70. #  define HEIGHT_10THS           117     /* 297mm */
  71. #endif
  72.  
  73. /* Define bits-per-pixel for generic drivers - default is 24-bit mode */
  74. #ifndef BITSPERPIXEL
  75. #  define BITSPERPIXEL 24
  76. #endif
  77.  
  78. #define W sizeof(word)
  79. #define I sizeof(int)
  80.  
  81. /* Printer types */
  82. #define DJ500C   0
  83. #define DJ550C   1
  84. #define PJXL300  2
  85. #define PJ180    3
  86. #define PJXL180  4
  87. #define DECLJ250 5
  88.  
  89. /* No. of ink jets (used to minimise head movements) */
  90. #define HEAD_ROWS_MONO 50
  91. #define HEAD_ROWS_COLOUR 16
  92.  
  93. /* Colour mapping procedures */
  94. private dev_proc_map_rgb_color (gdev_pcl_map_rgb_color);
  95. private dev_proc_map_color_rgb (gdev_pcl_map_color_rgb);
  96.  
  97. /* Print-page, properties and miscellaneous procedures */
  98. private dev_proc_open_device(dj500c_open);
  99. private dev_proc_open_device(dj550c_open);
  100. private dev_proc_open_device(pjxl300_open);
  101. private dev_proc_open_device(pjxl_open);
  102. private dev_proc_open_device(pj_open);
  103. private dev_proc_print_page(dj500c_print_page);
  104. private dev_proc_print_page(dj550c_print_page);
  105. private dev_proc_print_page(pjxl_print_page);
  106. private dev_proc_print_page(pj_print_page);
  107. private dev_proc_print_page(pjxl300_print_page);
  108. private dev_proc_print_page(declj250_print_page);
  109. private dev_proc_get_props(cdj_get_props);
  110. private dev_proc_get_props(pjxl_get_props);
  111. private dev_proc_get_props(pj_get_props);
  112. private dev_proc_put_props(cdj_put_props);
  113. private dev_proc_put_props(pjxl_put_props);
  114. private dev_proc_put_props(pj_put_props);
  115.  
  116. /* The device descriptors */
  117. typedef struct gx_device_cdj_s gx_device_cdj;
  118. struct gx_device_cdj_s {
  119.         gx_device_common;
  120.         gx_prn_device_common;
  121.     int correction;           /* Black correction parameter */
  122.     int shingling;          /* Interlaced, multi-pass printing */
  123.     int depletion;          /* 'Intelligent' dot-removal */
  124. };
  125.  
  126. typedef struct gx_device_pjxl_s gx_device_pjxl;
  127. struct gx_device_pjxl_s {
  128.         gx_device_common;
  129.         gx_prn_device_common;
  130.     uint correction;          /* Black correction parameter */
  131.     int printqual;            /* Mechanical print quality */
  132.     int rendertype;           /* Driver or printer dithering control */
  133. };
  134.  
  135. typedef struct gx_device_hp_s gx_device_hp;
  136. struct gx_device_hp_s {
  137.         gx_device_common;
  138.         gx_prn_device_common;
  139.     uint correction;          /* Black correction parameter
  140.                    * (used only by DJ500C) */
  141. };
  142.  
  143. typedef struct gx_device_hp_s gx_device_pj;
  144.  
  145. #define hp_device ((gx_device_hp *)pdev)
  146. #define cdj       ((gx_device_cdj *)pdev)
  147. #define pjxl      ((gx_device_pjxl *)pdev)
  148. #define pj    ((gx_device_pj *)pdev)
  149.  
  150. #define prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page)\
  151.     prn_device_body(gx_device_printer, procs, dev_name,\
  152.     WIDTH_10THS, HEIGHT_10THS, x_dpi, y_dpi, 0, 0, 0, 0, 0,\
  153.     bpp, 0, 0, 0, 0, print_page)
  154.  
  155. #define cdj_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page, correction, shingling, depletion)\
  156. { prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page),\
  157.     correction,\
  158.     shingling,\
  159.     depletion\
  160. }
  161.  
  162. #define pjxl_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page, printqual, rendertype)\
  163. { prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page), 0, \
  164.     printqual,\
  165.     rendertype\
  166. }
  167.  
  168. #define pj_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page)\
  169. { prn_hp_colour_device(procs, dev_name, x_dpi, y_dpi, bpp, print_page), 0\
  170. }
  171.  
  172. #define hp_colour_procs(proc_colour_open, proc_get_props, proc_put_props) {\
  173.     proc_colour_open,\
  174.     gdev_pcl_get_initial_matrix,\
  175.     gx_default_sync_output,\
  176.     gdev_prn_output_page,\
  177.     gdev_prn_close,\
  178.     gdev_pcl_map_rgb_color,\
  179.     gdev_pcl_map_color_rgb,\
  180.     NULL,    /* fill_rectangle */\
  181.     NULL,    /* tile_rectangle */\
  182.     NULL,    /* copy_mono */\
  183.     NULL,    /* copy_color */\
  184.     NULL,    /* draw_line */\
  185.     gx_default_get_bits,\
  186.     proc_get_props,\
  187.     proc_put_props\
  188. }
  189.  
  190. private gx_device_procs cdj500_procs =
  191. hp_colour_procs(dj500c_open, cdj_get_props, cdj_put_props);
  192.  
  193. private gx_device_procs cdj550_procs =
  194. hp_colour_procs(dj550c_open, cdj_get_props, cdj_put_props);
  195.  
  196. private gx_device_procs pjxl300_procs =
  197. hp_colour_procs(pjxl300_open, pjxl_get_props, pjxl_put_props);
  198.  
  199. private gx_device_procs pjxl_procs =
  200. hp_colour_procs(pjxl_open, pjxl_get_props, pjxl_put_props);
  201.  
  202. private gx_device_procs pj_procs =
  203. hp_colour_procs(pj_open, pj_get_props, pj_put_props);
  204.  
  205. gx_device_cdj far_data gs_cdjmono_device =
  206. cdj_device(cdj500_procs, "cdjmono", 300, 300, 1,
  207.        dj500c_print_page, 4, 0, 1);
  208.  
  209. gx_device_cdj far_data gs_cdeskjet_device =
  210. cdj_device(cdj500_procs, "cdeskjet", 300, 300, 3,
  211.        dj500c_print_page, 4, 2, 1);
  212.  
  213. gx_device_cdj far_data gs_cdjcolor_device =
  214. cdj_device(cdj500_procs, "cdjcolor", 300, 300, 24,
  215.        dj500c_print_page, 4, 2, 1);
  216.  
  217. gx_device_cdj far_data gs_cdj500_device =
  218. cdj_device(cdj500_procs, "cdj500", 300, 300, BITSPERPIXEL,
  219.        dj500c_print_page, 4, 2, 1);
  220.  
  221. gx_device_cdj far_data gs_cdj550_device =
  222. cdj_device(cdj550_procs, "cdj550", 300, 300, BITSPERPIXEL,
  223.        dj550c_print_page, 0, 2, 1);
  224.  
  225. gx_device_pjxl far_data gs_pjxl300_device =
  226. pjxl_device(pjxl300_procs, "pjxl300", 300, 300, BITSPERPIXEL,
  227.        pjxl300_print_page, 0, 0);
  228.  
  229. gx_device_pjxl far_data gs_pjxl_device =
  230. pjxl_device(pjxl_procs, "pjxl", 180, 180, BITSPERPIXEL,
  231.        pjxl_print_page, 0, 0);
  232.  
  233. gx_device_pj far_data gs_pj_device =
  234. pj_device(pj_procs, "pj", 180, 180, BITSPERPIXEL,
  235.        pj_print_page);
  236.  
  237. gx_device_pj far_data gs_declj250_device =
  238. pj_device(pj_procs, "declj250", 180, 180, BITSPERPIXEL,
  239.        declj250_print_page);
  240.  
  241. /* Forward references */
  242. private int gdev_pcl_mode1compress(P3(const byte *, const byte *, byte *));
  243. private int gdev_pcl_mode9compress(P4(int, const byte *, const byte *, byte *));
  244. private int hp_colour_open(P2(gx_device *, int));
  245. private int hp_colour_print_page(P3(gx_device_printer *, FILE *, int));
  246. private int put_prop_int(P5(gs_prop_item *, int *, int, int, int));
  247. private uint gdev_prn_rasterwidth(P2(const gx_device_printer *, int));
  248. private void set_bpp(P2(gx_device *, int));
  249. private void expand_line(P4(word *, int, int, int));
  250.  
  251. /* Open the printer and set up the margins. */
  252. private int
  253. dj500c_open(gx_device *pdev)
  254. { return hp_colour_open(pdev, DJ500C);
  255. }
  256.  
  257. private int
  258. dj550c_open(gx_device *pdev)
  259. { return hp_colour_open(pdev, DJ550C);
  260. }
  261.  
  262. private int
  263. pjxl300_open(gx_device *pdev)
  264. { return hp_colour_open(pdev, PJXL300);
  265. }
  266.  
  267. private int
  268. pj_open(gx_device *pdev)
  269. { return hp_colour_open(pdev, PJ180);
  270. }
  271.  
  272. private int
  273. pjxl_open(gx_device *pdev)
  274. { return hp_colour_open(pdev, PJXL180);
  275. }
  276.  
  277. private int
  278. hp_colour_open(gx_device *pdev, int ptype)
  279. {       /* Change the margins if necessary. */
  280.   static const float pj_a4[4] = { PAINTJET_MARGINS_A4 };
  281.   static const float pj_a3[4] = { PAINTJET_MARGINS_A3 };
  282.   static const float pj_letter[4] = { PAINTJET_MARGINS_LETTER };
  283.   static const float dj_a4[4] = { DESKJET_MARGINS_A4 };
  284.   static const float dj_letter[4] = { DESKJET_MARGINS_LETTER };
  285.   const float _ds *m;
  286.   int psize;
  287.  
  288.   /* Set up colour params if put_props has not already done so */
  289.   if (pdev->color_info.num_components == 0)
  290.     set_bpp(pdev, pdev->color_info.depth);
  291.  
  292.   switch (ptype) {
  293.   case DJ500C:
  294.   case DJ550C:
  295.     m = (gdev_pcl_paper_size(pdev) == PAPER_SIZE_A4 ? dj_a4 :
  296.      dj_letter);
  297.     break;
  298.   case PJ180:
  299.     m = (gdev_pcl_paper_size(pdev) == PAPER_SIZE_A4 ? pj_a4 :
  300.      pj_letter);
  301.     break;
  302.   case PJXL300:
  303.   case PJXL180:
  304.     m = ((psize = gdev_pcl_paper_size(pdev)) == PAPER_SIZE_A4 ? pj_a4 :
  305.      (psize == PAPER_SIZE_A3) ? pj_a3 : pj_letter);
  306.     break;
  307.   }
  308.   pdev->l_margin = m[0];
  309.   pdev->b_margin = m[1];
  310.   pdev->r_margin = m[2];
  311.   pdev->t_margin = m[3];
  312.   return gdev_prn_open(pdev);
  313. }
  314.  
  315. /* Added properties for DeskJet 5xxC */
  316.  
  317. private const gs_prop_item props_cdj[] = {
  318.   /* Read-write properties. */
  319.   prop_def("BlackCorrect", prt_int),
  320.   prop_def("Shingling", prt_int),
  321.   prop_def("Depletion", prt_int),
  322.   prop_def("BitsPerPixel", prt_int),
  323. };
  324.  
  325. /* Get properties.  In addition to the standard and printer 
  326.  * properties, we supply shingling and depletion parameters,
  327.  * and control over the bits-per-pixel used in output rendering */
  328. private int
  329. cdj_get_props(gx_device *pdev, gs_prop_item *plist)
  330. {    int start = gdev_prn_get_props(pdev, plist);
  331.     if ( plist != 0 )
  332.        {    register gs_prop_item *pi = plist + start;
  333.         memcpy(pi, props_cdj, sizeof(props_cdj));
  334.         pi[0].value.i = cdj->correction;
  335.         pi[1].value.i = cdj->shingling;
  336.         pi[2].value.i = cdj->depletion;
  337.         pi[3].value.i = cdj->color_info.depth;
  338.        }
  339.     return start + sizeof(props_cdj) / sizeof(gs_prop_item);
  340. }
  341.  
  342. /* Put properties. */
  343. private int
  344. cdj_put_props(gx_device *pdev, gs_prop_item *plist, int count)
  345. {    gs_prop_item *known[4];
  346.     int old_bpp = cdj->color_info.depth;
  347.     int bpp = 0;
  348.     int code = 0;
  349.  
  350.     props_extract(plist, count, props_cdj, 4, known, 0);
  351.     code = gdev_prn_put_props(pdev, plist, count);
  352.     if ( code < 0 ) return code;
  353.  
  354.     code = put_prop_int(known[0], &cdj->correction, 0, 9, code);
  355.     code = put_prop_int(known[1], &cdj->shingling, 0, 2, code);
  356.     code = put_prop_int(known[2], &cdj->depletion, 1, 3, code);
  357.     code = put_prop_int(known[3], &bpp, 1, 32, code);
  358.  
  359.     if ( code < 0 )
  360.       return_error(code);
  361.  
  362.     if (bpp != 0) {
  363.       set_bpp(pdev, bpp);
  364.       
  365.       /* Close the device; gs_putdeviceprops will reopen it. */
  366.       if ( bpp != old_bpp && pdev->is_open )
  367.         { int ccode = gs_closedevice(pdev);
  368.           if ( ccode < 0 ) return ccode;
  369.         }
  370.     }
  371.     
  372.     return code;
  373. }
  374.  
  375. /* Added properties for PaintJet XL and PaintJet XL300 */
  376.  
  377. private const gs_prop_item props_pjxl[] = {
  378.   /* Read-write properties. */
  379.   prop_def("PrintQuality", prt_int),
  380.   prop_def("RenderType", prt_int),
  381.   prop_def("BitsPerPixel", prt_int),
  382. };
  383.  
  384. /* Get properties.  In addition to the standard and printer
  385.  * properties, we supply print_quality and render_type 
  386.  * parameters, together with bpp control. */
  387. private int
  388. pjxl_get_props(gx_device *pdev, gs_prop_item *plist)
  389. {    int start = gdev_prn_get_props(pdev, plist);
  390.     if ( plist != 0 )
  391.        {    register gs_prop_item *pi = plist + start;
  392.         memcpy(pi, props_pjxl, sizeof(props_pjxl));
  393.         pi[0].value.i = pjxl->printqual;
  394.         pi[1].value.i = pjxl->rendertype;
  395.         pi[2].value.i = pjxl->color_info.depth;
  396.        }
  397.     return start + sizeof(props_pjxl) / sizeof(gs_prop_item);
  398. }
  399.  
  400. /* Put properties. */
  401. private int
  402. pjxl_put_props(gx_device *pdev, gs_prop_item *plist, int count)
  403. {    gs_prop_item *known[3];
  404.     int old_bpp = pjxl->color_info.depth;
  405.     int bpp = 0;
  406.     int code = 0;
  407.  
  408.     props_extract(plist, count, props_pjxl, 3, known, 0);
  409.     code = gdev_prn_put_props(pdev, plist, count);
  410.     if ( code < 0 ) return code;
  411.  
  412.     code = put_prop_int(known[0], &pjxl->printqual, -1, 1, code);
  413.     code = put_prop_int(known[1], &pjxl->rendertype, 0, 10, code);
  414.     code = put_prop_int(known[2], &bpp, 1, 32, code);
  415.  
  416.     if ( code < 0 )
  417.       return_error(code);
  418.  
  419.     if (pjxl->rendertype > 0) {
  420.       /* If printer is doing the dithering, we must have a
  421.        * true-colour mode, ie. 16 or 24 bits per pixel */
  422.       if ((bpp == 0 && old_bpp < 16) || (bpp > 0 && bpp < 16))
  423.         bpp = 24;
  424.     }
  425.  
  426.     if (bpp != 0) {
  427.       set_bpp(pdev, bpp);
  428.       
  429.       /* Close the device; gs_putdeviceprops will reopen it. */
  430.       if ( bpp != old_bpp && pdev->is_open )
  431.         { int ccode = gs_closedevice(pdev);
  432.           if ( ccode < 0 ) return ccode;
  433.         }
  434.     }
  435.     
  436.     return code;
  437. }
  438.  
  439. /* Added properties for PaintJet */
  440.  
  441. private const gs_prop_item props_pj[] = {
  442.   /* Read-write properties. */
  443.   prop_def("BitsPerPixel", prt_int),
  444. };
  445.  
  446. /* Get properties.  In addition to the standard and printer */
  447. /* properties, we allow control of the bits-per-pixel */
  448. private int
  449. pj_get_props(gx_device *pdev, gs_prop_item *plist)
  450. {    int start = gdev_prn_get_props(pdev, plist);
  451.     if ( plist != 0 )
  452.        {    register gs_prop_item *pi = plist + start;
  453.         memcpy(pi, props_pj, sizeof(props_pj));
  454.         pi[0].value.i = pj->color_info.depth;
  455.        }
  456.     return start + sizeof(props_pj) / sizeof(gs_prop_item);
  457. }
  458.  
  459. /* Put properties. */
  460. private int
  461. pj_put_props(gx_device *pdev, gs_prop_item *plist, int count)
  462. {    gs_prop_item *known[1];
  463.     int old_bpp = pj->color_info.depth;
  464.     int bpp = 0;
  465.     int code = 0;
  466.  
  467.     props_extract(plist, count, props_pj, 1, known, 0);
  468.     code = gdev_prn_put_props(pdev, plist, count);
  469.     if ( code < 0 ) return code;
  470.  
  471.     code = put_prop_int(known[0], &bpp, 1, 32, code);
  472.  
  473.     if ( code < 0 )
  474.       return_error(code);
  475.  
  476.     if (bpp != 0) {
  477.       set_bpp(pdev, bpp);
  478.       
  479.       /* Close the device; gs_putdeviceprops will reopen it. */
  480.       if ( bpp != old_bpp && pdev->is_open )
  481.         { int ccode = gs_closedevice(pdev);
  482.           if ( ccode < 0 ) return ccode;
  483.         }
  484.     }
  485.     
  486.     return code;
  487. }
  488.  
  489. /* ------ Internal routines ------ */
  490.  
  491. /* The DeskJet500C can compress (mode 9) */
  492. private int
  493. dj500c_print_page(gx_device_printer * pdev, FILE * prn_stream)
  494. {
  495.   return hp_colour_print_page(pdev, prn_stream, DJ500C);
  496. }
  497.  
  498. /* The DeskJet550C can compress (mode 9) */
  499. private int
  500. dj550c_print_page(gx_device_printer * pdev, FILE * prn_stream)
  501. {
  502.   return hp_colour_print_page(pdev, prn_stream, DJ550C);
  503. }
  504.  
  505. /* The PJXL300 can compress (modes 2 & 3) */
  506. private int
  507. pjxl300_print_page(gx_device_printer * pdev, FILE * prn_stream)
  508. { int ret_code;
  509.   /* Ensure we're operating in PCL mode */
  510.   fputs("\033%-12345X@PJL enter language = PCL\n", prn_stream);
  511.   ret_code = hp_colour_print_page(pdev, prn_stream, PJXL300);
  512.   /* Reenter switch-configured language */
  513.   fputs("\033%-12345X", prn_stream);
  514.   return ret_code;
  515. }
  516.  
  517. /* The PaintJet XL can compress (modes 2 & 3) */
  518. private int
  519. pjxl_print_page(gx_device_printer * pdev, FILE * prn_stream)
  520. {
  521.   return hp_colour_print_page(pdev, prn_stream, PJXL180);
  522. }
  523.  
  524. /* The PaintJet can compress (mode 1) */
  525. private int
  526. pj_print_page(gx_device_printer * pdev, FILE * prn_stream)
  527. {
  528.   return hp_colour_print_page(pdev, prn_stream, PJ180);
  529. }
  530.  
  531. /* The LJ250 can compress (mode 1) */
  532. private int
  533. declj250_print_page(gx_device_printer * pdev, FILE * prn_stream)
  534. { int ret_code;
  535.   fputs("\033%8", prn_stream);    /* Enter PCL emulation mode */
  536.   ret_code = hp_colour_print_page(pdev, prn_stream, DECLJ250);
  537.   fputs("\033%@", prn_stream);    /* Exit PCL emulation mode */
  538.   return ret_code;
  539. }
  540.  
  541. /* MACROS FOR DITHERING (we use macros for compact source and faster code) */
  542. /* Floyd-Steinberg dithering. Often results in a dramatic improvement in
  543.  * subjective image quality, but can also produce dramatic increases in
  544.  * amount of printer data generated and actual printing time!! Mode 9 2D
  545.  * compression is still useful for fairly flat colour or blank areas but its
  546.  * compression is much less effective in areas where the dithering has
  547.  * effectively randomised the dot distribution. */
  548.  
  549. #define SHIFT (I * I)
  550. #define MINVALUE  0
  551. #define MAXVALUE  ((256 << SHIFT) - 1)
  552. #define THRESHOLD (128 << SHIFT)
  553.  
  554. #define FSditherI(inP, out, errP, Err, Bit, Offset)\
  555.     oldErr = Err;\
  556.     Err = (*errP + ((Err * 7) >> 4) + (*inP++ << SHIFT));\
  557.         if (Err > MAXVALUE) Err = MAXVALUE;\
  558.         else if (Err < MINVALUE) Err = MINVALUE;\
  559.     if (Err > THRESHOLD) {\
  560.       out |= Bit;\
  561.       Err -= MAXVALUE;\
  562.     }\
  563.     errP[Offset] += ((Err * 3) >> 4);\
  564.     *errP++ = ((Err * 5 + oldErr) >> 4);
  565.  
  566. #define FSditherD(inP, out, errP, Err, Bit, Offset)\
  567.     oldErr = Err;\
  568.     Err = (*--errP + ((Err * 7) >> 4) + (*--inP << SHIFT));\
  569.         if (Err > MAXVALUE) Err = MAXVALUE;\
  570.         else if (Err < MINVALUE) Err = MINVALUE;\
  571.     if (Err > THRESHOLD) {\
  572.       out |= Bit;\
  573.       Err -= MAXVALUE;\
  574.     }\
  575.     errP[Offset] += ((Err * 3) >> 4);\
  576.     *errP = ((Err * 5 + oldErr) >> 4);
  577.  
  578. /* Here we rely on compiler optimisation to remove lines of the form
  579.  * (if (1 >= 4) {...}, ie. the constant boolean expressions */
  580.  
  581. #define FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr, cP, mP, yP, kP, n)\
  582. {\
  583.     if (scan == 0) {       /* going_up */\
  584.       for (i = 0; i < plane_size; i++) {\
  585.     byte c, y, m, k, bitmask;\
  586.     int oldErr;\
  587.     bitmask = 0x80;\
  588.     for (c = m = y = k = j = 0; j < 8; j++) {\
  589.       if (n >= 4)\
  590.         { FSditherI(dp, k, ep, kErr, bitmask, -n);\
  591.         }\
  592.       if (n >= 3)\
  593.         { FSditherI(dp, c, ep, cErr, bitmask, -n);\
  594.           FSditherI(dp, m, ep, mErr, bitmask, -n);\
  595.         }\
  596.       FSditherI(dp, y, ep, yErr, bitmask, -n);\
  597.       bitmask >>= 1;\
  598.     }\
  599.     if (n >= 4)\
  600.       *kP++ = k;\
  601.     if (n >= 3)\
  602.       { *cP++ = c;\
  603.             *mP++ = m;\
  604.       }\
  605.         *yP++ = y;\
  606.       }\
  607.     } else {        /* going_down */\
  608.       for (i = 0; i < plane_size; i++) {\
  609.     byte c, y, m, k, bitmask;\
  610.     int oldErr;\
  611.     bitmask = 0x01;\
  612.     for (c = m = y = k = j = 0; j < 8; j++) {\
  613.       FSditherD(dp, y, ep, yErr, bitmask, n);\
  614.       if (n >= 3)\
  615.         { FSditherD(dp, m, ep, mErr, bitmask, n);\
  616.           FSditherD(dp, c, ep, cErr, bitmask, n);\
  617.         }\
  618.       if (n >= 4)\
  619.         { FSditherD(dp, k, ep, kErr, bitmask, n);\
  620.         }\
  621.       bitmask <<= 1;\
  622.     }\
  623.     *--yP = y;\
  624.     if (n >= 3)\
  625.       { *--mP = m;\
  626.         *--cP = c;\
  627.       }\
  628.     if (n >= 4)\
  629.       *--kP = k;\
  630.       }\
  631.     }\
  632. }
  633. /* END MACROS FOR DITHERING */
  634.  
  635. /* Some convenient shorthand .. */
  636. #define x_dpi        (pdev->x_pixels_per_inch)
  637. #define y_dpi        (pdev->y_pixels_per_inch)
  638. #define CONFIG_16BIT "\033*v6W\000\003\000\005\006\005"
  639. #define CONFIG_24BIT "\033*v6W\000\003\000\010\010\010"
  640.  
  641. /* To calculate buffer size as next greater multiple of both parameter and W */
  642. #define calc_buffsize(a, b) (((((a) + ((b) * W) - 1) / ((b) * W))) * W)
  643.  
  644. /* Send the page to the printer.  Compress each scan line. */
  645. private int
  646. hp_colour_print_page(gx_device_printer * pdev, FILE * prn_stream, int ptype)
  647. {
  648.   uint raster_width = gdev_prn_rasterwidth(pdev, 1);
  649. /*  int line_size = gdev_prn_rasterwidth(pdev, 0); */
  650.   int line_size = gdev_prn_raster(pdev);
  651.   int line_size_words = (line_size + W - 1) / W;
  652.   int paper_size = gdev_pcl_paper_size((gx_device *)pdev);
  653.   int num_comps = pdev->color_info.num_components;
  654.   int bits_per_pixel = pdev->color_info.depth;
  655.   int storage_bpp = bits_per_pixel;
  656.   int expanded_bpp = bits_per_pixel;
  657.   int plane_size, databuff_size;
  658.   int combined_escapes = 1;
  659.   int errbuff_size = 0;
  660.   int outbuff_size = 0;
  661.   int compression = 0;
  662.   int scan = 0;
  663.   int *errors[2];
  664.   char *cid_string;
  665.   byte *data[4], *plane_data[4][4], *out_data;
  666.   byte *out_row, *out_row_alt;
  667.   word *storage;
  668.   uint storage_size_words;
  669.  
  670.   /* Tricks and cheats ... */
  671.   switch (ptype) {
  672.   case DJ550C:
  673.     if (num_comps == 3)
  674.       num_comps = 4;                      /* 4-component printing */
  675.     break;
  676.   case PJXL300:
  677.   case PJXL180:
  678.     if (pjxl->rendertype > 0) {
  679.       if (bits_per_pixel < 16)
  680.     pjxl->rendertype = 0;
  681.       else {
  682.     /* Control codes for CID sequence */
  683.     cid_string = (bits_per_pixel == 16) ? CONFIG_16BIT : CONFIG_24BIT;
  684.     /* Pretend we're a monobit device so we send the data out unchanged */
  685.     bits_per_pixel = storage_bpp = expanded_bpp = 1;
  686.     num_comps = 1;
  687.       }
  688.     }
  689.     break;
  690.   }
  691.  
  692.   if (storage_bpp == 8 && num_comps >= 3)
  693.     bits_per_pixel = expanded_bpp = 3;  /* Only 3 bits of each byte used */
  694.  
  695.   plane_size = calc_buffsize(line_size, storage_bpp);
  696.  
  697.   if (bits_per_pixel == 1) {            /* Data printed direct from i/p */
  698.     databuff_size = 0;                  /* so no data buffer required, */
  699.     outbuff_size = plane_size * 4;      /* but need separate output buffers */
  700.   }
  701.   
  702.   if (bits_per_pixel > 4) {             /* Error buffer for FS dithering */
  703.     expanded_bpp = storage_bpp =        /* 8, 24 or 32 bits */
  704.       num_comps * 8;
  705.     errbuff_size =                      /* 4n extra values for line ends */
  706.       calc_buffsize((plane_size * expanded_bpp + num_comps * 4) * I, 1);
  707.   }
  708.  
  709.   databuff_size = plane_size * storage_bpp;
  710.  
  711.   storage_size_words = ((plane_size + plane_size) * num_comps +
  712.             databuff_size + errbuff_size + outbuff_size) / W;
  713.  
  714.   storage = (ulong *) gs_malloc(storage_size_words, W, "hp_colour_print_page");
  715.  
  716.   /*
  717.    * The principal data pointers are stored as pairs of values, with
  718.    * the selection being made by the 'scan' variable. The function of the
  719.    * scan variable is overloaded, as it controls both the alternating
  720.    * raster scan direction used in the Floyd-Steinberg dithering and also
  721.    * the buffer alternation required for line-difference compression.
  722.    *
  723.    * Thus, the number of pointers required is as follows:
  724.    * 
  725.    *   errors:      2  (scan direction only)
  726.    *   data:        4  (scan direction and alternating buffers)
  727.    *   plane_data:  4  (scan direction and alternating buffers)
  728.    */
  729.  
  730.   if (storage == 0)        /* can't allocate working area */
  731.     return_error(gs_error_VMerror);
  732.   else {
  733.     int i;
  734.     byte *p = out_data = out_row = (byte *)storage;    
  735.     data[0] = data[1] = data[2] = p;
  736.     data[3] = p + databuff_size;
  737.     out_row_alt = out_row + plane_size * 2;
  738.     if (bits_per_pixel > 1) {
  739.       p += databuff_size;
  740.     }
  741.     if (bits_per_pixel > 4) {
  742.       errors[0] = (int *)p + num_comps * 2;
  743.       errors[1] = errors[0] + databuff_size;
  744.       p += errbuff_size;
  745.     }
  746.     for (i = 0; i < num_comps; i++) {
  747.       plane_data[0][i] = plane_data[2][i] = p;
  748.       p += plane_size;
  749.     }
  750.     for (i = 0; i < num_comps; i++) {
  751.       plane_data[1][i] = p;
  752.       plane_data[3][i] = p + plane_size;
  753.       p += plane_size;
  754.     }
  755.     if (bits_per_pixel == 1) {
  756.       out_data = out_row = p;      /* size is outbuff_size * 4 */
  757.       out_row_alt = out_row + plane_size * 2;
  758.       data[1] += databuff_size;   /* coincides with plane_data pointers */
  759.       data[3] += databuff_size;
  760.     }
  761.   }
  762.   
  763.   /* Clear temp storage */
  764.   memset(storage, 0, storage_size_words * W);
  765.   
  766.   /* Initialize printer. */
  767.   fputs("\033E", prn_stream);                       /* Reset printer */
  768.   fputs("\033*rbC", prn_stream);                   /* End raster graphics */
  769.   fprintf(prn_stream, "\033*t%dR", (int)x_dpi);       /* Set resolution */
  770.  
  771. #define DOFFSET (pdev->t_margin - DESKJET_PRINT_LIMIT)  /* Print position */
  772. #define POFFSET (pdev->t_margin - PAINTJET_PRINT_LIMIT)
  773.   switch (ptype) {
  774.   case DJ500C:
  775.   case DJ550C:
  776.     /* Page size, orientation, top margin & perforation skip */
  777.     fprintf(prn_stream, "\033&l%daolE", paper_size);
  778.     /* Set depletion and shingling levels */
  779.     fprintf(prn_stream, "\033*o%dd%dQ", cdj->depletion, cdj->shingling);
  780.     /* Move to top left of printed area */
  781.     fprintf(prn_stream, "\033*p%dY", (int)(300 * DOFFSET));
  782.     /* Set number of planes ((-)1 is mono, (-)3 is (cmy)rgb, -4 is cmyk),
  783.      * and raster width, then start raster graphics */
  784.     fprintf(prn_stream, "\033*r%ds-%du0A", raster_width, num_comps);
  785.     /* Select data compression */
  786.     compression = 9;
  787.     break;
  788.   case PJXL300:
  789.     /* Page size, orientation, top margin & perforation skip */
  790.     fprintf(prn_stream, "\033&l%daolE", paper_size);
  791.     /* Set no-negative-motion mode, for faster (unbuffered) printing */
  792.     fprintf(prn_stream, "\033&a1N");
  793.     /* Set print quality */
  794.     fprintf(prn_stream, "\033*o%dQ", pjxl->printqual);
  795.     /* Move to top left of printed area */
  796.     fprintf(prn_stream, "\033*p%dY", (int)(300 * POFFSET));
  797.     /* Configure colour setup */
  798.     if (pjxl->rendertype > 0) {
  799.       /* Set render type */
  800.       fprintf(prn_stream, "\033*t%dJ", pjxl->rendertype);
  801.       /* Configure image data */
  802.       fputs(cid_string, prn_stream);
  803.       /* Set raster width, then start raster graphics */
  804.       fprintf(prn_stream, "\033*r%ds1A", raster_width);
  805.     } else {
  806.       /* Set number of planes (1 is mono, 3 is rgb),
  807.        * and raster width, then start raster graphics */
  808.       fprintf(prn_stream, "\033*r%ds-%du0A", raster_width, num_comps);
  809.     }
  810.     /* No combined escapes for raster transfers */
  811.     combined_escapes = 0;
  812.     break;
  813.   case PJXL180:
  814.     /* Page size, orientation, top margin & perforation skip */
  815.     fprintf(prn_stream, "\033&l%daolE", paper_size);
  816.     /* Set print quality */
  817.     fprintf(prn_stream, "\033*o%dQ", pjxl->printqual);
  818.     /* Move to top left of printed area */
  819.     fprintf(prn_stream, "\033*p%dY", (int)(180 * POFFSET));
  820.     /* Configure colour setup */
  821.     if (pjxl->rendertype > 0) {
  822.       /* Set render type */
  823.       fprintf(prn_stream, "\033*t%dJ", pjxl->rendertype);
  824.       /* Configure image data */
  825.       fputs(cid_string, prn_stream);
  826.       /* Set raster width, then start raster graphics */
  827.       fprintf(prn_stream, "\033*r%ds1A", raster_width);
  828.     } else {
  829.       /* Set number of planes (1 is mono, 3 is rgb),
  830.        * and raster width, then start raster graphics */
  831.       fprintf(prn_stream, "\033*r%ds%du0A", raster_width, num_comps);
  832.     }
  833.     break;
  834.   case PJ180:
  835.   case DECLJ250:
  836.     /* Disable perforation skip */
  837.     fprintf(prn_stream, "\033&lL");
  838.     /* Move to top left of printed area */
  839.     fprintf(prn_stream, "\033&a%dV", (int)(720 * POFFSET));
  840.     /* Set number of planes (1 is mono, 3 is rgb),
  841.      * and raster width, then start raster graphics */
  842.     fprintf(prn_stream, "\033*r%ds%du0A", raster_width, num_comps);
  843.     if (ptype == DECLJ250) {
  844.       /* No combined escapes for raster transfers */
  845.       combined_escapes = 0;
  846.       /* From here on, we're a standard Paintjet .. */
  847.       ptype = PJ180;
  848.     }
  849.     /* Select data compression */
  850.     compression = 1;
  851.     break;
  852.   }
  853.  
  854.   /* The XL300 PCL interpreter seems to be based on a rather old definition
  855.    * of the language - although it is newer than the deskjets, it includes
  856.    * neither the 'mode 9' compression, nor (even more suprisingly) the ability
  857.    * to use combined escape sequences for the raster transfer commands
  858.    * (where they make by far the biggest impact). Technically, it is a 
  859.    * language extension, but the previous model (the 180dpi Paintjet XL)
  860.    * has this facility, which means that the XL300 is non-backwards-compatible
  861.    * in this respect. Even the original and venerable 180dpi Paintjet has the
  862.    * 'extension'. I have made a guess that the DEC LJ250 does not support
  863.    * it, but have not yet found somebody to test this for me. */
  864.  
  865.   if (combined_escapes) {
  866.     /* From now on, all escape commands start with \033*b, so we
  867.      * combine them. */
  868.     fputs("\033*b", prn_stream);
  869.      /* Set compression if the mode has been defined. */
  870.     if (compression)
  871.       fprintf(prn_stream, "%dm", compression);
  872.   } else
  873.     if (compression)
  874.       fprintf(prn_stream, "\033*b%dM", compression);
  875.  
  876.   /* Send each scan line in turn */
  877.   {
  878.     int lend = pdev->height - (pdev->t_margin + pdev->b_margin) * y_dpi;
  879.     int cErr, mErr, yErr, kErr;
  880.     int this_pass, lnum, i;
  881.     int num_blank_lines = 0;
  882.     int start_rows = (num_comps == 1) ?
  883.       HEAD_ROWS_MONO - 1 : HEAD_ROWS_COLOUR - 1;
  884.     word rmask = ~(word) 0 << ((-pdev->width * storage_bpp) & (W * 8 - 1));
  885.  
  886.     cErr = mErr = yErr = kErr = 0;
  887.  
  888.     if (bits_per_pixel > 4) { /* Randomly seed initial error buffer */
  889.       int *ep = errors[0];
  890.       for (i = 0; i < databuff_size; i++) {
  891.     *ep++ = (rand() % (MAXVALUE / 2))  - MAXVALUE / 4;
  892.       }
  893.     }
  894.  
  895.     /* Inhibit blank line printing for RGB-only printers, 
  896.      * since in this case 'blank' means black! */
  897.     if (ptype == PJ180 || ptype == PJXL180) start_rows = -1;
  898.  
  899.     this_pass = start_rows;
  900.     for (lnum = 0; lnum < lend; lnum++) {
  901.       word *data_words = (word *)data[scan];
  902.       register word *end_data = data_words + line_size_words;
  903.  
  904.       gdev_prn_copy_scan_lines(pdev, lnum, data[scan], line_size);
  905.  
  906.       /* Mask off 1-bits beyond the line width. */
  907.       end_data[-1] &= rmask;
  908.  
  909.       /* Remove trailing 0s. */
  910.       while (end_data > data_words && end_data[-1] == 0)
  911.     end_data--;
  912.       if (end_data == data_words) {    /* Blank line */
  913.     num_blank_lines++;
  914.     continue;
  915.       }
  916.       /* Skip blank lines if any */
  917.       if (num_blank_lines > 0) {
  918.     if (num_blank_lines < this_pass) {
  919.       /* Moving down from current position
  920.        * causes head motion on the DeskJets, so
  921.        * if the number of lines is within the
  922.        * current pass of the print head, we're
  923.        * better off printing blanks. */
  924.       this_pass -= num_blank_lines;
  925.       if (combined_escapes) {
  926.         fputc('y', prn_stream);   /* Clear current and seed rows */
  927.         for (; num_blank_lines; num_blank_lines--)
  928.           fputc('w', prn_stream);
  929.       } else {
  930.         fputs("\033*bY", prn_stream);   /* Clear current and seed rows */
  931.         for (; num_blank_lines; num_blank_lines--)
  932.           fputs("\033*bW", prn_stream);
  933.       }
  934.     } else {
  935.       if (combined_escapes)
  936.         fprintf(prn_stream, "%dy", num_blank_lines);
  937.       else
  938.         fprintf(prn_stream, "\033*b%dY", num_blank_lines);
  939.     }
  940.     memset(plane_data[1 - scan][0], 0, plane_size * num_comps);
  941.     num_blank_lines = 0;
  942.     this_pass = start_rows;
  943.       }
  944.       {            /* Printing non-blank lines */
  945.     register byte *kP = plane_data[scan + 2][3];
  946.     register byte *cP = plane_data[scan + 2][2];
  947.     register byte *mP = plane_data[scan + 2][1];
  948.     register byte *yP = plane_data[scan + 2][0];
  949.     register byte *dp = data[scan + 2];
  950.     register int *ep = errors[scan];
  951.     int zero_row_count;
  952.     int i, j;
  953.     byte *odp;
  954.  
  955.     if (this_pass)
  956.       this_pass--;
  957.     else
  958.       this_pass = start_rows;
  959.  
  960.     if (expanded_bpp > bits_per_pixel)   /* Expand line if required */
  961.       expand_line(data_words, line_size, bits_per_pixel, expanded_bpp);
  962.  
  963.     /* In colour modes, we have some bit-shuffling to do before
  964.      * we can print the data; in FS mode we also have the
  965.      * dithering to take care of. */
  966.     switch (expanded_bpp) {    /* Can be 1, 3, 8, 24 or 32 */
  967.     case 3:
  968.       /* Transpose the data to get pixel planes. */
  969.       for (i = 0, odp = plane_data[scan][0]; i < databuff_size;
  970.            i += 8, odp++) {    /* The following is for 16-bit
  971.                  * machines */
  972. #define spread3(c)\
  973.     { 0, c, c*0x100, c*0x101, c*0x10000L, c*0x10001L, c*0x10100L, c*0x10101L }
  974.         static ulong spr40[8] = spread3(0x40);
  975.         static ulong spr08[8] = spread3(8);
  976.         static ulong spr02[8] = spread3(2);
  977.         register byte *dp = data[scan] + i;
  978.         register ulong pword =
  979.         (spr40[dp[0]] << 1) +
  980.         (spr40[dp[1]]) +
  981.         (spr40[dp[2]] >> 1) +
  982.         (spr08[dp[3]] << 1) +
  983.         (spr08[dp[4]]) +
  984.         (spr08[dp[5]] >> 1) +
  985.         (spr02[dp[6]]) +
  986.         (spr02[dp[7]] >> 1);
  987.         odp[0] = (byte) (pword >> 16);
  988.         odp[plane_size] = (byte) (pword >> 8);
  989.         odp[plane_size * 2] = (byte) (pword);
  990.       }
  991.       break;
  992.  
  993.     case 8:
  994.       FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr,
  995.           cP, mP, yP, kP, 1);
  996.       break;
  997.     case 24:
  998.       FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr,
  999.           cP, mP, yP, kP, 3);
  1000.       break;
  1001.     case 32:
  1002.       FSDline(scan, i, j, plane_size, cErr, mErr, yErr, kErr,
  1003.           cP, mP, yP, kP, 4);
  1004.       break;
  1005.  
  1006.     } /* switch(expanded_bpp) */
  1007.  
  1008.     /* Make sure all black is in the k plane */
  1009.         if (num_comps == 4 ) {
  1010.       register word *kp = (word *)plane_data[scan][3];
  1011.       register word *cp = (word *)plane_data[scan][2];
  1012.       register word *mp = (word *)plane_data[scan][1];
  1013.       register word *yp = (word *)plane_data[scan][0];
  1014.       if (bits_per_pixel > 4) {  /* This has been done as 4 planes */
  1015.         for (i = 0; i < plane_size / W; i++) {
  1016.           word bits = ~*kp++;
  1017.           *cp++ &= bits;
  1018.           *mp++ &= bits;
  1019.           *yp++ &= bits;
  1020.         }
  1021.       } else {  /* This has really been done as 3 planes */
  1022.         for (i = 0; i < plane_size / W; i++) {
  1023.           word bits = *cp & *mp & *yp;
  1024.           *kp++ = bits;
  1025.           bits = ~bits;
  1026.           *cp++ &= bits;
  1027.           *mp++ &= bits;
  1028.           *yp++ &= bits;
  1029.         }
  1030.       }
  1031.         }
  1032.  
  1033.     /* Transfer raster graphics
  1034.      * in the order (K), C, M, Y. */
  1035.     for (zero_row_count = 0, i = num_comps - 1; i >= 0; i--) {
  1036.       int output_plane = 1;
  1037.       int out_count;
  1038.       
  1039.       switch (ptype) {
  1040.       case DJ500C:    /* Always compress using mode 9 */
  1041.       case DJ550C:
  1042.         out_count = gdev_pcl_mode9compress(plane_size,
  1043.                            plane_data[scan][i],
  1044.                            plane_data[1 - scan][i],
  1045.                            out_data);
  1046.  
  1047.         /* This optimisation allows early termination of the
  1048.          * row, but this doesn't work correctly in an alternating
  1049.          * mode 2 / mode 3 regime, so we only use it with mode 9
  1050.          * compression */
  1051.            if (out_count == 0)
  1052.              { output_plane = 0;      /* No further output for this plane */
  1053.                if (i == 0)
  1054.                  fputc('w', prn_stream);
  1055.                else
  1056.                  zero_row_count++;
  1057.              }
  1058.            else
  1059.              { for (; zero_row_count; zero_row_count--)
  1060.                  fputc('v', prn_stream);
  1061.              }
  1062.         break;
  1063.       case PJ180:
  1064.         /* NB: The mode 1 routine complements the data -> rgb */
  1065.         out_count = gdev_pcl_mode1compress((const byte *)
  1066.                            plane_data[scan][i],
  1067.                            (const byte *)
  1068.                            plane_data[scan][i] + plane_size - 1,
  1069.                            out_data);
  1070.         break;
  1071.       case PJXL180:    /* Need to invert data as CMY not supported */
  1072.         if (num_comps > 1)
  1073.           { word *wp = (word *)plane_data[scan][i];
  1074.         for (j = 0; j < plane_size / W; j++, wp++)
  1075.           *wp = ~*wp;
  1076.           }
  1077.         /* fall through .. */
  1078.       case PJXL300:     /* Compression modes 2 and 3 are both 
  1079.                  * available.  Try both and see which one
  1080.                  * produces the least output data. */
  1081.         { const char *plane = (char *)plane_data[scan][i];
  1082.           char *prev_plane = (char *)plane_data[1 - scan][i];
  1083.           const word *row = (word *)plane;
  1084.           const word *end_row = row + plane_size/W;
  1085.           int count2 = gdev_pcl_mode2compress(row, end_row, out_row_alt);
  1086.           int count3 = gdev_pcl_mode3compress(plane_size, plane, prev_plane, out_row);
  1087.           int penalty = combined_escapes ? strlen("#m") : strlen("\033*b#M");
  1088.           int penalty2 = (compression == 2 ? 0 : penalty);
  1089.           int penalty3 = (compression == 3 ? 0 : penalty);
  1090.           
  1091.           if (count3 + penalty3 < count2 + penalty2)
  1092.         { if ( compression != 3 ) {
  1093.             if (combined_escapes)
  1094.               fputs("3m", prn_stream);
  1095.             else
  1096.               fputs("\033*b3M", prn_stream);
  1097.             compression = 3;
  1098.           }
  1099.           out_data = out_row;
  1100.           out_count = count3;
  1101.         }
  1102.           else
  1103.         { if ( compression != 2 ) {
  1104.             if (combined_escapes)
  1105.               fputs("2m", prn_stream);
  1106.             else
  1107.               fputs("\033*b2M", prn_stream);
  1108.             compression = 2;
  1109.           }
  1110.           out_data = out_row_alt;
  1111.           out_count = count2;
  1112.         }
  1113.         }
  1114.         break;
  1115.       }
  1116.       if (output_plane) {
  1117.         if (combined_escapes)
  1118.           fprintf(prn_stream, "%d%c", out_count, "wvvv"[i]);
  1119.         else
  1120.           fprintf(prn_stream, "\033*b%d%c", out_count, "WVVV"[i]);
  1121.         fwrite(out_data, sizeof(byte), out_count, prn_stream);
  1122.       }
  1123.       
  1124.     } /* Transfer Raster Graphics ... */
  1125.     scan = 1 - scan;          /* toggle scan direction */
  1126.       }      /* Printing non-blank lines */
  1127.     }     /* for lnum ... */
  1128.   }       /* send each scan line in turn */
  1129.  
  1130.   if (combined_escapes)
  1131.     fputs("0M", prn_stream);
  1132.  
  1133.   /* end raster graphics & reset printer */
  1134.   fputs("\033*rbC\033E", prn_stream);
  1135.  
  1136.   /* eject page */
  1137.   if (ptype == PJ180)
  1138.     fputc('\f', prn_stream);
  1139.   else
  1140.     fputs("\033&l0H", prn_stream);
  1141.  
  1142.   /* free temporary storage */
  1143.   gs_free((char *) storage, storage_size_words, W, "hp_colour_print_page");
  1144.  
  1145.   return 0;
  1146. }
  1147.  
  1148. /*
  1149.  * Mode 9 2D compression for the HP DeskJet 5xxC. This mode can give
  1150.  * very good compression ratios, especially if there are areas of flat
  1151.  * colour (or blank areas), and so is 'highly recommended' for colour
  1152.  * printing in particular because of the very large amounts of data which
  1153.  * can be generated
  1154.  */
  1155. private int
  1156. gdev_pcl_mode9compress(int bytecount, const byte * current, const byte * previous, byte * compressed)
  1157. {
  1158.   register const byte *cur = current;
  1159.   register const byte *prev = previous;
  1160.   register byte *out = compressed;
  1161.   const byte *end = current + bytecount;
  1162.  
  1163.   while (cur < end) {        /* Detect a run of unchanged bytes. */
  1164.     const byte *run = cur;
  1165.     register const byte *diff;
  1166.     int offset;
  1167.     while (cur < end && *cur == *prev) {
  1168.       cur++, prev++;
  1169.     }
  1170.     if (cur == end)
  1171.       break;            /* rest of row is unchanged */
  1172.     /* Detect a run of changed bytes. */
  1173.     /* We know that *cur != *prev. */
  1174.     diff = cur;
  1175.     do {
  1176.       prev++;
  1177.       cur++;
  1178.     }
  1179.     while (cur < end && *cur != *prev);
  1180.     /* Now [run..diff) are unchanged, and */
  1181.     /* [diff..cur) are changed. */
  1182.     offset = diff - run;
  1183.     {
  1184.       const byte *stop_test = cur - 4;
  1185.       int dissimilar, similar;
  1186.  
  1187.       while (diff < cur) {
  1188.     const byte *compr = diff;
  1189.     const byte *next;    /* end of run */
  1190.     byte value;
  1191.     while (diff <= stop_test &&
  1192.            ((value = *diff) != diff[1] ||
  1193.         value != diff[2] ||
  1194.         value != diff[3]))
  1195.       diff++;
  1196.  
  1197.     /* Find out how long the run is */
  1198.     if (diff > stop_test)    /* no run */
  1199.       next = diff = cur;
  1200.     else {
  1201.       next = diff + 4;
  1202.       while (next < cur && *next == value)
  1203.         next++;
  1204.     }
  1205.  
  1206. #define MAXOFFSETU 15
  1207. #define MAXCOUNTU 7
  1208.     /* output 'dissimilar' bytes, uncompressed */
  1209.     if ((dissimilar = diff - compr)) {
  1210.       int temp, i;
  1211.  
  1212.       if ((temp = --dissimilar) > MAXCOUNTU)
  1213.         temp = MAXCOUNTU;
  1214.       if (offset < MAXOFFSETU)
  1215.         *out++ = (offset << 3) | (byte) temp;
  1216.       else {
  1217.         *out++ = (MAXOFFSETU << 3) | (byte) temp;
  1218.         offset -= MAXOFFSETU;
  1219.         while (offset >= 255) {
  1220.           *out++ = 255;
  1221.           offset -= 255;
  1222.         }
  1223.         *out++ = offset;
  1224.       }
  1225.       if (temp == MAXCOUNTU) {
  1226.         temp = dissimilar - MAXCOUNTU;
  1227.         while (temp >= 255) {
  1228.           *out++ = 255;
  1229.           temp -= 255;
  1230.         }
  1231.         *out++ = (byte) temp;
  1232.       }
  1233.       for (i = 0; i <= dissimilar; i++)
  1234.         *out++ = *compr++;
  1235.       offset = 0;
  1236.     }            /* end uncompressed */
  1237. #define MAXOFFSETC 3
  1238. #define MAXCOUNTC 31
  1239.     /* output 'similar' bytes, run-length encoded */
  1240.     if ((similar = next - diff)) {
  1241.       int temp;
  1242.  
  1243.       if ((temp = (similar -= 2)) > MAXCOUNTC)
  1244.         temp = MAXCOUNTC;
  1245.       if (offset < MAXOFFSETC)
  1246.         *out++ = 0x80 | (offset << 5) | (byte) temp;
  1247.       else {
  1248.         *out++ = 0x80 | (MAXOFFSETC << 5) | (byte) temp;
  1249.         offset -= MAXOFFSETC;
  1250.         while (offset >= 255) {
  1251.           *out++ = 255;
  1252.           offset -= 255;
  1253.         }
  1254.         *out++ = offset;
  1255.       }
  1256.       if (temp == MAXCOUNTC) {
  1257.         temp = similar - MAXCOUNTC;
  1258.         while (temp >= 255) {
  1259.           *out++ = 255;
  1260.           temp -= 255;
  1261.         }
  1262.         *out++ = (byte) temp;
  1263.       }
  1264.       *out++ = value;
  1265.       offset = 0;
  1266.     }            /* end compressed */
  1267.     diff = next;
  1268.       }
  1269.     }
  1270.   }
  1271.   return out - compressed;
  1272. }
  1273.  
  1274. /*
  1275.  * Row compression for the H-P PaintJet.
  1276.  * Compresses data from row up to end_row, storing the result
  1277.  * starting at compressed.  Returns the number of bytes stored.
  1278.  * The compressed format consists of a byte N followed by a
  1279.  * data byte that is to be repeated N+1 times.
  1280.  * In the worst case, the `compressed' representation is
  1281.  * twice as large as the input.
  1282.  * We complement the bytes at the same time, because
  1283.  * we accumulated the image in complemented form.
  1284.  */
  1285. private int
  1286. gdev_pcl_mode1compress(const byte *row, const byte *end_row, byte *compressed)
  1287. {       register const byte *in = row;
  1288.         register byte *out = compressed;
  1289.         while ( in < end_row )
  1290.            {    byte test = *in++;
  1291.                 const byte *run = in;
  1292.                 while ( in < end_row && *in == test ) in++;
  1293.                 /* Note that in - run + 1 is the repetition count. */
  1294.                 while ( in - run > 255 )
  1295.                    {    *out++ = 255;
  1296.                         *out++ = ~test;
  1297.                         run += 256;
  1298.                    }
  1299.                 *out++ = in - run;
  1300.                 *out++ = ~test;
  1301.            }
  1302.         return out - compressed;
  1303. }
  1304.  
  1305. /*
  1306.  * Map a r-g-b color to a color index.
  1307.  * We complement the colours, since we're using cmy anyway, and
  1308.  * because the buffering routines expect white to be zero.
  1309.  * Includes colour balancing, following HP recommendations, to try
  1310.  * and correct the greenish cast resulting from an equal mix of the
  1311.  * c, m, y, inks by reducing the cyan component to give a truer black.
  1312.  */
  1313. private gx_color_index
  1314. gdev_pcl_map_rgb_color(gx_device *pdev, gx_color_value r,
  1315.                  gx_color_value g, gx_color_value b)
  1316. {
  1317.   if (gx_color_value_to_byte(r & g & b) == 0xff)
  1318.     return (gx_color_index)0;         /* white */
  1319.   else {
  1320.     int correction = hp_device->correction;
  1321.     gx_color_value c = gx_max_color_value - r;
  1322.     gx_color_value m = gx_max_color_value - g;
  1323.     gx_color_value y = gx_max_color_value - b;
  1324.     
  1325.     /* Colour correction for better blacks when using the colour ink
  1326.      * cartridge (on the DeskJet 500C only). We reduce the cyan component
  1327.      * by some fraction (eg. 4/5) to correct the slightly greenish cast
  1328.      * resulting from an equal mix of the three inks */
  1329.     if (correction) {
  1330.       ulong maxval, minval, range;
  1331.       
  1332.       maxval = c >= m ? (c >= y ? c : y) : (m >= y ? m : y);
  1333.       if (maxval > 0) {
  1334.     minval = c <= m ? (c <= y ? c : y) : (m <= y? m : y);
  1335.     range = maxval - minval;
  1336.     
  1337. #define shift (gx_color_value_bits - 12)
  1338.     c = ((c >> shift) * (range + (maxval * correction))) /
  1339.       ((maxval * (correction + 1)) >> shift);
  1340.       }
  1341.     }
  1342.     
  1343.     switch (pdev->color_info.depth) {
  1344.     case 1:
  1345.       return ((c | m | y) > gx_max_color_value / 2 ?
  1346.           (gx_color_index)1 : (gx_color_index)0);
  1347.     case 8:
  1348.       if (pdev->color_info.num_components >= 3)
  1349. #define gx_color_value_to_1bit(cv) ((cv) >> (gx_color_value_bits - 1))
  1350.     return (gx_color_value_to_1bit(c) +
  1351.         (gx_color_value_to_1bit(m) << 1) +
  1352.         (gx_color_value_to_1bit(y) << 2));
  1353.       else
  1354. #define red_weight 306
  1355. #define green_weight 601
  1356. #define blue_weight 117
  1357.     return ((((ulong)c * red_weight +
  1358.           (ulong)m * green_weight +
  1359.           (ulong)y * blue_weight)
  1360.          >> (gx_color_value_bits + 2)));
  1361.     case 16:
  1362. #define gx_color_value_to_5bits(cv) ((cv) >> (gx_color_value_bits - 5))
  1363. #define gx_color_value_to_6bits(cv) ((cv) >> (gx_color_value_bits - 6))
  1364.       return (gx_color_value_to_5bits(y) +
  1365.           (gx_color_value_to_6bits(m) << 5) +
  1366.           (gx_color_value_to_5bits(c) << 11));
  1367.     case 24:
  1368.       return (gx_color_value_to_byte(y) +
  1369.           (gx_color_value_to_byte(m) << 8) +
  1370.           ((ulong)gx_color_value_to_byte(c) << 16));
  1371.     case 32:
  1372.       { gx_color_value k = c <= m ? (c <= y ? c : y) : (m <= y ? m : y);
  1373.     return (gx_color_value_to_byte(y - k) +
  1374.         (gx_color_value_to_byte(m - k) << 8) +
  1375.         ((ulong)gx_color_value_to_byte(c - k) << 16) +
  1376.         ((ulong)gx_color_value_to_byte(k) << 24));
  1377.       }
  1378.     }
  1379.   }
  1380.   return (gx_color_index)0;   /* This never happens */
  1381. }
  1382.     
  1383. /* Map a color index to a r-g-b color. */
  1384. private int
  1385. gdev_pcl_map_color_rgb(gx_device *pdev, gx_color_index color,
  1386.                 gx_color_value prgb[3])
  1387. {
  1388.   /* For the moment, we simply ignore any black correction */
  1389.   switch (pdev->color_info.depth) {
  1390.   case 1:
  1391.     prgb[0] = prgb[1] = prgb[2] = -((gx_color_value)color ^ 1);
  1392.     break;
  1393.   case 8:
  1394.       if (pdev->color_info.num_components >= 3)
  1395.     { gx_color_value c = (gx_color_value)color ^ 7;
  1396.       prgb[0] = -(c & 1);
  1397.       prgb[1] = -((c >> 1) & 1);
  1398.       prgb[2] = -(c >> 2);
  1399.     }
  1400.       else
  1401.     { gx_color_value value = (gx_color_value)color ^ 0xff;
  1402.       prgb[0] = prgb[1] = prgb[2] = (value << 8) + value;
  1403.     }
  1404.     break;
  1405.   case 16:
  1406.     { gx_color_value c = (gx_color_value)color ^ 0xffff;
  1407.       ushort value = c >> 11;
  1408.       prgb[0] = ((value << 11) + (value << 6) + (value << 1) +
  1409.          (value >> 4)) >> (16 - gx_color_value_bits);
  1410.       value = (c >> 6) & 0x3f;
  1411.       prgb[1] = ((value << 10) + (value << 4) + (value >> 2))
  1412.     >> (16 - gx_color_value_bits);
  1413.       value = c & 0x1f;
  1414.       prgb[2] = ((value << 11) + (value << 6) + (value << 1) +
  1415.          (value >> 4)) >> (16 - gx_color_value_bits);
  1416.     }
  1417.     break;
  1418.   case 24:
  1419.     { gx_color_value c = (gx_color_value)color ^ 0xffffff;
  1420.       prgb[0] = gx_color_value_from_byte(c >> 16);
  1421.       prgb[1] = gx_color_value_from_byte((c >> 8) & 0xff);
  1422.       prgb[2] = gx_color_value_from_byte(c & 0xff);
  1423.     }
  1424.     break;
  1425.   case 32:
  1426. #define  gx_maxcol gx_color_value_from_byte(gx_color_value_to_byte(gx_max_color_value))
  1427.     { gx_color_value w = gx_maxcol - gx_color_value_from_byte(color >> 24);
  1428.       prgb[0] = w - gx_color_value_from_byte((color >> 16) & 0xff);
  1429.       prgb[1] = w - gx_color_value_from_byte((color >> 8) & 0xff);
  1430.       prgb[2] = w - gx_color_value_from_byte(color & 0xff);
  1431.     }
  1432.     break;
  1433.   }
  1434.   return 0;
  1435. }
  1436.  
  1437. /*
  1438.  * Convert and expand scanlines:
  1439.  *
  1440.  *       (a)    16 -> 24 bit   (1-stage)
  1441.  *       (b)    16 -> 32 bit   (2-stage)
  1442.  *   or  (c)    24 -> 32 bit   (1-stage)
  1443.  */
  1444. private void
  1445. expand_line(word *line, int linesize, int bpp, int ebpp)
  1446. {
  1447.   int endline = linesize;
  1448.   byte *start = (byte *)line;
  1449.   register byte *in, *out;
  1450.  
  1451.   if (bpp == 16)              /* 16 to 24 (cmy) if required */
  1452.     { register byte b0, b1;
  1453.       endline = ((endline + 1) / 2);
  1454.       in = start + endline * 2;
  1455.       out = start + (endline *= 3);
  1456.       
  1457.       while (in > start)
  1458.     { b0 = *--in;
  1459.       b1 = *--in;
  1460.       *--out = (b0 << 3) + ((b0 >> 2) & 0x7);
  1461.       *--out = (b1 << 5) + ((b0 >> 3)  & 0x1c) + ((b1 >> 1) & 0x3);
  1462.       *--out = (b1 & 0xf8) + (b1 >> 5);
  1463.     }
  1464.     }
  1465.  
  1466.   if (ebpp == 32)             /* 24 (cmy) to 32 (cmyk) if required */
  1467.     { register byte c, m, y, k;
  1468.       endline = ((endline + 2) / 3);
  1469.       in = start + endline * 3;
  1470.       out = start + endline * 4;
  1471.  
  1472.       while (in > start)
  1473.     { y = *--in;
  1474.       m = *--in;
  1475.       c = *--in;
  1476.       k = c < m ? (c < y ? c : y) : (m < y ? m : y);
  1477.       *--out = y - k;
  1478.       *--out = m - k;
  1479.       *--out = c - k;
  1480.       *--out = k;
  1481.     }
  1482.     }
  1483. }
  1484.  
  1485. private int
  1486. put_prop_int(gs_prop_item *pi, int *property, int minval, int maxval, int code)
  1487. {
  1488.   if ( pi == 0 )
  1489.     return (code);
  1490.   
  1491.   if ( pi->value.i < minval || pi->value.i > maxval )
  1492.     { pi->status = pv_rangecheck;
  1493.       return (gs_error_rangecheck);
  1494.     }
  1495.   else
  1496.     { *property = pi->value.i;
  1497.       return (code ? code : 1);
  1498.     }
  1499. }    
  1500.  
  1501. private void
  1502. set_bpp(gx_device *pdev, int bits_per_pixel)
  1503. { gx_device_color_info *ci = &pdev->color_info;
  1504.   /* Only valid bits-per-pixel are 1, 3, 8, 16, 24, 32 */
  1505.   int bpp = bits_per_pixel < 3 ? 1 : bits_per_pixel < 8 ? 3 : 
  1506.     (bits_per_pixel >> 3) << 3;
  1507.   ci->num_components = ((bpp == 1) || (bpp == 8) ? 1 : 3);
  1508.   ci->depth = ((bpp > 1) && (bpp < 8) ? 8 : bpp);
  1509.   ci->max_gray = (bpp >= 8 ? 255 : 1);
  1510.   ci->max_rgb = (bpp >= 8 ? 255 : bpp > 1 ? 1 : 0);
  1511.   ci->dither_gray = (bpp >= 8 ? 5 : 2);
  1512.   ci->dither_rgb = (bpp >= 8 ? 5 : bpp > 1 ? 2 : 0);
  1513. }
  1514.  
  1515. /* This returns either the number of pixels in a scan line, or the number
  1516.  * of bytes required to store the line, both clipped to the page margins */
  1517. private uint
  1518. gdev_prn_rasterwidth(const gx_device_printer *pdev, int pixelcount)
  1519. {
  1520.   ulong raster_width =
  1521.     pdev->width - pdev->x_pixels_per_inch * (pdev->l_margin + pdev->r_margin);
  1522.   return (pixelcount ?
  1523.           (uint)raster_width :
  1524.           (uint)((raster_width * pdev->color_info.depth + 7) >> 3));
  1525. }
  1526.